package com.engineering.elink.service.impl;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.engineering.elink.domain.AuthUser;
import com.engineering.elink.service.OAuthApiService;
import com.engineering.elink.util.ConfigUtil;
import com.engineering.elink.util.tool.UUIDUtil;


/**
 * qq第三方登录
 * 第一步：授权，获取code
 * 第二步：通过code,获取accessToken
 * 第三步：通过accessToken,获取openid
 * 第四步:通过accessToken、openid获取用户信息
 * @author GunnyZeng
 *
 */
@Service(value="qqAuth")
public class QQOAuthApiServiceImpl implements OAuthApiService{

	private String app_ID =    ConfigUtil.getValue("qq_app_ID").trim();
	private String app_KEY =    ConfigUtil.getValue("qq_app_KEY").trim();
	private String redirect_URI = ConfigUtil.getValue("qq_redirect_URI").trim();
	private String scope = ConfigUtil.getValue("qq_scope").trim();
	private String getUserInfoURL = ConfigUtil.getValue("qq_getUserInfoURL").trim();
	private String authorizeURL = ConfigUtil.getValue("qq_authorizeURL").trim();
	private String accessTokenURL = ConfigUtil.getValue("qq_accessTokenURL").trim();
	private String getOpenIDURL = ConfigUtil.getValue("qq_getOpenIDURL").trim();

	@Override
	public String authorize() {
		String state = UUIDUtil.getUUID();
        if(scope != null && !scope.equals(""))
        	 return (new StringBuilder()).append(authorizeURL).append("?client_id=").append(app_ID).append("&redirect_uri=").append(redirect_URI).append("&response_type=").append("code").append("&state=").append(state).append("&scope=").append(scope).toString();
        else
            return (new StringBuilder()).append(authorizeURL).append("?client_id=").append(app_ID).append("&redirect_uri=").append(redirect_URI).append("&response_type=").append("code").append("&state=").append(state).toString();
	}

	@Override
	public AuthUser getUser(Object parame) throws Exception {
		 String code = (String) parame;
	 	String token = getToken(code);
         AuthUser user =  new AuthUser();
         if (token.equals("")) {
             throw new Exception("授权失败！");
         } else {

             // 利用获取到的accessToken 去获取当前用的openid -------- start
             String openID = getOpenID(token);
             //获取用户信息
             JSONObject json = showUser(openID,token);
             if (json!=null) {
                 user.setId(openID);
                 user.setAvatarLarge(json.getString("figureurl"));
                 user.setNickName(json.getString("nickname"));
                 user.setGender(json.getString("gender"));
                 user.setSource("QQ");
             } else {
            	 throw new Exception("很抱歉，我们没能正确获取到您的信息! ");
             }
         }
         return user;
	}
	
	/**
	 * 获取AccessToken
	 * @param code
	 * @return
	 * @throws Exception 
	 */
//	private AccessToken getAccessToken(String code) throws Exception{
//		return new AccessToken(client.post(
//				accessTokenURL,
//				new PostParameter[] {
//						new PostParameter("client_id", app_ID),
//						new PostParameter("client_secret",app_KEY),
//						new PostParameter("grant_type", "authorization_code"),
//						new PostParameter("code", code),
//						new PostParameter("redirect_uri", redirect_URI) }, false, null),"openid");
//	}
	/**
	 * 授权后获取用户json数据
	 * @param accessToken
	 * @return
	 * @throws Exception 
	 */
//	 private JSONObject showUser(String openid,AccessToken accessToken) throws Exception
//		    {
//		        return client.get(getUserInfoURL, new PostParameter[] {
//		            new PostParameter("openid", openid), 
//		            new PostParameter("oauth_consumer_key", app_ID), 
//		            new PostParameter("access_token", accessToken.getAccessToken()), 
//		            new PostParameter("format", "json")
//		        },accessToken.getAccessToken()).asJSONObject();
//		    }
	 /**
	  * 获取openID
	  * @param accessToken
	  * @return
	  * @throws Exception
	  */
//	 private String getOpenID(AccessToken accessToken) throws Exception{
//		 String openid = "";
//		 String jsonp = client.get(getOpenIDURL, 
//				 new PostParameter[] {
//		            new PostParameter("access_token", accessToken.getAccessToken())
//		        },accessToken.getAccessToken()).asString();
//		 Matcher m = Pattern.compile("\"openid\"\\s*:\\s*\"(\\w+)\"").matcher(jsonp);
//	        if(m.find())
//	            openid = m.group(1);
//	        else
//	            throw new Exception("server error!");
//	        return openid;
//	 }
	 
	 
	 
	 
	 /**
	  * 获取token 
	  * @param code
	  * @return
	  * @throws HttpException
	  * @throws IOException
	  */
	private    String getToken (String code) throws HttpException, IOException{
			HttpClient client=new HttpClient();
			HttpMethod method=new GetMethod(accessTokenURL);
			method.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf8");
			
			NameValuePair[] data = { 
					new NameValuePair("client_id", app_ID),
					new NameValuePair("client_secret",app_KEY),
					new NameValuePair("grant_type", "authorization_code"),
					new NameValuePair("code", code),
					new NameValuePair("redirect_uri", redirect_URI)
			};
			method.setQueryString(data);
			client.executeMethod(method);
			if(method.getStatusCode() == 200){
				 String  tokenString = method.getResponseBodyAsString();
				 if(tokenString != null){
					 return   tokenString.substring(tokenString.indexOf("access_token=")+13, tokenString.indexOf("access_token=")+32+13);
				 }
			}
			return null;
		}
	 
	 private  String getOpenID(String token) throws Exception{
			HttpClient client=new HttpClient();
			HttpMethod method=new GetMethod(getOpenIDURL);
			method.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf8");
			NameValuePair[] data = { 
					new NameValuePair("access_token", token)
			};
			method.setQueryString(data);
			client.executeMethod(method);
			if(method.getStatusCode() == 200){
				 String  openIdString = method.getResponseBodyAsString();
				 if(openIdString != null){
					 return  openIdString.substring(openIdString.indexOf("openid")+9, openIdString.indexOf("openid")+9+32);
				 }
			}
			return null;
	 }

	 /**
	  * 授权后获取用户json数据
	  * @param openid
	  * @param token
	  * @return
	  * @throws Exception
	  */
	 private   JSONObject showUser(String openid,String token) throws Exception {
			HttpClient client=new HttpClient();
			HttpMethod method=new GetMethod(getUserInfoURL);
			method.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf8");
			
			NameValuePair[] data = { 
					new NameValuePair("openid", openid),
					new NameValuePair("oauth_consumer_key", app_ID),
					new NameValuePair("access_token", token),
					new NameValuePair("format", "json")
			};
			method.setQueryString(data);
			client.executeMethod(method);
			if(method.getStatusCode() == 200){
				 return  JSONObject.parseObject(method.getResponseBodyAsString());
			}
			return null;
	    }
	 
}
